package com.gzhu.knowledgeAdmin.parammanage;


import com.gzhu.knowledgeAdmin.common.dto.param.ParamAddRequest;
import com.gzhu.knowledgeAdmin.common.dto.param.ParamDeleteRequest;
import com.gzhu.knowledgeAdmin.common.dto.param.ParamGetRequest;
import com.gzhu.knowledgeAdmin.common.exception.BusinessException;
import com.gzhu.knowledgeAdmin.common.result.ErrorCode;
import com.gzhu.knowledgeAdmin.repository.DenoiseLevelRepository;
import com.gzhu.knowledgeAdmin.entity.DenoiseLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DenoiseLevelParamCRUD implements ParamCRUD<DenoiseLevel>{

    @Autowired
    private DenoiseLevelRepository denoiseLevelRepository;

    @Override
    public List<String> getSimpleList() {
        List<DenoiseLevel> denoiseLevelList = denoiseLevelRepository.findAll();
        return denoiseLevelList.stream().map(denoiseLevel -> denoiseLevel.getName()).collect(Collectors.toList());
    }

    @Override
    public Page<DenoiseLevel> getList(ParamGetRequest paramGetRequest) {
        DenoiseLevel denoiseLevel = new DenoiseLevel();
        denoiseLevel.setName(paramGetRequest.getValue());

        ExampleMatcher matcher = ExampleMatcher.matching()
                //contains 模糊匹配
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());

        Example<DenoiseLevel> example = Example.of(denoiseLevel, matcher);

        Pageable pageable = PageRequest.of(paramGetRequest.getPageNum() - 1, paramGetRequest.getPageSize());

        return denoiseLevelRepository.findAll(example, pageable);
    }

    @Override
    public void addParam(ParamAddRequest paramAddRequest) {
        String value = paramAddRequest.getValue();

        DenoiseLevel denoiseLevelByName = denoiseLevelRepository.getDenoiseLevelByName(value);
        if (denoiseLevelByName != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"对应参数已经存在");
        }

        DenoiseLevel denoiseLevel = new DenoiseLevel();
        denoiseLevel.setName(value);
        denoiseLevelRepository.save(denoiseLevel);
    }

    @Override
    public void deleteParam(ParamDeleteRequest paramDeleteRequest) {
        List<Integer> ids = paramDeleteRequest.getIds();

        denoiseLevelRepository.deleteAllByIdInBatch(ids);
    }
}
